package com.itheima.ydd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.mapper.RoleMapper;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public List<String> roleNameList(String role_id) {
        String[] strings = role_id.split(",");
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getId, strings);
        List<Role> roles = this.list(roleLambdaQueryWrapper);
        List<String> roleNameList = CollUtil.getFieldValues(roles, "name", String.class);
        return roleNameList;
    }

    @Override
    public void removeRMM(String id) {
        //根据sys_role表id去用户表查询User,如果结果大于0就抛异常
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole_id, id);
        int count = userService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("该角色下由用户不允许删除!");
        }

        //直接把sys_role表根据id删除
        roleService.removeById(id);


        //根据id查询sys_role_menu表,把查询到的数据根据id删除
        LambdaQueryWrapper<RoleMenu> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(RoleMenu::getRole_id, id);

        roleMenuService.remove(queryWrapper1);


    }
}
